<template>
  <div v-show="fileType === 'pdf'" class="pdf">
    <p v-if="pageCount>1 && page" class="arrow">
      <span class="turn" :class="{grey: currentPage==1}" @click="changePdfPage(0)">上一页</span>
      {{ currentPage }} / {{ pageCount }}
      <span class="turn" :class="{grey: currentPage==pageCount}" @click="changePdfPage(1)">下一页</span>
    </p>
    <div @click="previewHandle">
      <pdf
        :src="src"
        style="width: 100%"
        :page="currentPage"
        @num-pages="pageCount=$event"
        @page-loaded="currentPage=$event"
        @loaded="loadPdfHandler"
      > // 加载事件
      </pdf>
    </div>

    <template v-if="preview">
      <el-dialog
        width="70%"
        title="PDF预览"
        :visible.sync="innerVisible"
        append-to-body
        class="viewpdf-info"
      >
        <wise-pdf :file-src="fileSrc" :page="true"/>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
export default {
  name: 'WisePdf',
  components: {
    pdf
  },
  props: ['fileSrc', 'page', 'preview'],
  data() {
    return {
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      fileType: 'pdf', // 文件类型
      src: '',
      innerVisible: false
    }
  },
  created() {
    // 有时PDF文件地址会出现跨域的情况,这里最好处理一下
    this.src = this.fileSrc
  },
  methods: {
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
       
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        
      }
    },

    // pdf加载时
    loadPdfHandler(e) {
      
      this.currentPage = 1 // 加载的时候先加载第一页
    },
    previewHandle() {
      if (this.preview) {
        this.innerVisible = true
      }
    }

  }
}
</script>

<style scoped>

</style>
